<?php
class controller_PhotoController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {
        $user = model_UserMapper::getCurrentUser();
        if (null == $user->getId()) {
            $this->view->message = 'У вас нет доступа к этой функции!';
            $this->view->setRenderTemplate("error.phtml");
            return;
        } else {
            if(empty($this->args['action'])) {
                $this->index();
            } else {
                switch ($this->args['action']) {

                    case 'index':
                        $this->index();
                        break;

                    case 'edit':
                        $this->edit();
                        break;

                    case 'delete':
                        $this->delete();
                        break;

                    case 'save':
                        $this->save();
                        break;

                    default:
                        $this->index();
                }
            }
        }
    }

    public function index() {
        $mapper = new model_PhotoMapper();
        $user = model_UserMapper::getCurrentUser();

        if(empty($this->args['id'])) { //если id пустой, то отрисовывем все новости (fetchAll)

            if(empty($this->args['user'])) {
                $this->args['user'] = $user->getId();
            }

            $this->view->owner = $this->args['user'];
            $this->view->allModels = $mapper->fetchAll($this->args['user']);


            $this->view->setRenderTemplate("photo/indexFetchAll.phtml");

        } else { //если же он указан, то ищем новость с этим id

            $this->view->oneModel = $mapper->find($this->args['id']);


            if(null != $this->view->oneModel->getId()) {
                $this->view->owner = model_ConfigMapper::findOwner($this->args['id']);
                $this->view->allImgs = $mapper->fetchAll($this->view->owner);
                $this->view->setRenderTemplate("photo/indexFind.phtml");
            } else {
                $this->view->message = 'Такой фотографии нет';
                $this->view->link = '<a href="?controller=photo&action=index">К моим фотографиям</a>';
                $this->view->setRenderTemplate("error.phtml");
            }
        }
    }


    public function edit() {
        $mapper = new model_PhotoMapper();

        if(!empty($this->args['id'])) {
            $this->view->oneModel = $mapper->find($this->args['id']);
            $user = model_UserMapper::getCurrentUser();

            if($user->getId() != $this->view->oneModel->getOwner()) {
                $this->view->message = 'Отказано в доступе';
                $this->view->link = '<a href="index.php?controller=photo">К фотографиям</a>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
        }

        $this->view->setRenderTemplate("photo/edit.phtml");
    }

    public function delete() {
        $user = model_UserMapper::getCurrentUser();
        $mapper = new model_PhotoMapper();
        $message = $mapper->find($this->args['id']);

        if($user->getId() != $message->getOwner()) {
            $this->view->message = 'Отказано в доступе';
            $this->view->link = '<a href="index.php?controller=photo">К фотографиям</a>';
            $this->view->setRenderTemplate("error.phtml");
            return;
        }

        if(!empty($this->args['id'])) {
            $mapper->delete($this->args['id']);

            if ($user->getAvatar() == $this->args['id']) { //если юзер удаляет картинку, которая является его аватаром
                $userMapper = new model_UserMapper(); // , то даем ему нулевой аватар.
                $userMapper->saveAvatar('0', $user->getId());
            }
        }

        $this->view->link = 'index.php?controller=photo';
        $this->view->setRenderTemplate("redirect.phtml");
    }

    public function save() {

        if(!empty ($_POST)) {

            $uploaddir = 'stuff/images/saved/';
            $filename = model_ConfigMapper::getSalt(10);
            $uploadfile = $uploaddir.basename($filename);

            //TODO: проверку, жпег ли это
            $post = model_ConfigMapper::validate($_POST);
            $mapper = new model_PhotoMapper();
            $user = model_UserMapper::getCurrentUser();
            $model = new model_PhotoModel();

            if('' == $post['id']) {
                if ( false == move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile.'.jpg')) {
                    //TODO: проверку на размер файла/на его разширение
                    $this->view->message = 'Ошибка при загрузке файла!';
                    $this->view->oneModel = new model_PhotoModel();
                    $this->view->oneModel->setTitle($post['title']);
                    $this->view->setRenderTemplate("photo/edit.phtml");
                    return;
                }
            } else {
                $message = $mapper->find($post['id']);
                if ($message->getOwner() != $user->getId()) {
                    $this->view->message = 'Отказано в доступе';
                    $this->view->link = '<a href="index.php?controller=photo">К фотографиям</a>';
                    $this->view->setRenderTemplate("error.phtml");
                    return;
                }
            }

            $model->setId($post['id'])
                    ->setName($filename)
                    ->setOwner($user->getId())
                    ->setTitle($post['title']);

            $mapper->save($model);

            if ('' == $post['id']) {
                $post['id'] = mysql_insert_id();
            }

            $this->view->link = 'index.php?controller=photo&action=index&id='. $post['id'];
            $this->view->setRenderTemplate("redirect.phtml");
            return;



        } else {
            $this->view->message = 'Ошибка запроса';
            $this->view->setRenderTemplate("error.phtml");
            return;
        }
    }
}